package config

import (
	"bytes"
	"encoding/json"
	"github.com/pkg/errors"
	"io/ioutil"
	"log"
)

type Conf struct {
	Env		string `json:"env"`
	Server	string `json:"server"`
	Mysql	*DBConf	`json:"mysql"`
	Log 	*LogConf `json:"log"`
	Wxpay 	*PayConf `json:"wxpay"`
	Alipay 	*PayConf `json:"alipay"`
}

type DBConf struct {
	Host     string `json:"host"`
	Port     string `json:"port"`
	User     string `json:"user"`
	Password string `json:"password"`
	DB       string `json:"db"`
}

type LogConf struct {
	Path string `json:"path"`
	CronPath string `json:"cronpath"`
}

type PayConf struct {
	AppId 			string `json:"appid"`
	MchId 			string `json:"mchid"`
	PublicKey		string `json:"publicKey"`
	AppPublicKey	string `json:"appPublicKey"`
	PrivateKey		string `json:"privateKey"`
	ApiKey			string `json:"apiKey"`
}

var confs Conf

func init() {
	//confs = new(Conf)
	LoadConfig(`/data/www/go-admin-official/.env`)
	//fmt.Println(confs)
}

// load env
func GetEnv() bool {
	e := confs.Env
	if e == "prod" {
		return true
	}
	return false
}

// load server uri
func GetServerURI() string {
	suri := confs.Server
	if suri == "" {
		log.Fatalln("server uri not found")
	}
	return suri
}

// load db conf
func GetDBConf(engine string) (*DBConf, error) {
	var dbconf *DBConf
	if engine == "mysql" {
		dbconf = confs.Mysql
	}
	if dbconf == nil {
		return nil, errors.New("db config empty")
	}
	return dbconf, nil
}

// load log conf
func GetLogConf() (*LogConf, error) {
	logconf := confs.Log
	if logconf == nil {
		return nil, errors.New("log config empty")
	}
	return logconf, nil
}

// load pay conf
func GetPayConf(paytype string) (*PayConf, error) {
	if paytype == "wxpay" {
		return confs.Wxpay, nil
	}
	if paytype == "alipay" {
		return confs.Alipay, nil
	}
	return nil, errors.New("pay config empty")
}

//从配置文件中载入json字符串
func LoadConfig(path string) {
	buf, err := ioutil.ReadFile(path)
	if err != nil {
		log.Fatalln("load config env failed: ", err)
	}
	decoder := json.NewDecoder(bytes.NewReader(buf))
	decoder.UseNumber()
	err = decoder.Decode(&confs)
	//fmt.Println(Confs.Mysql, Confs.Alipay, Confs.Wxpay, Confs.Log)
	if err != nil {
		log.Fatalln("decode config env failed: ", err)
	}
}
